import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:xbr_gaode_amap/amap/src/types/marker.dart';
import 'package:xbr_gaode_amap/base/amap_flutter_base.dart';
import 'package:xbr_gaode_location/core/location.dart';
import 'package:xbr_gaode_location/xbr_gaode_location.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_button.dart';
import 'package:yt_devops/model/amap_poi.dart';
import 'package:yt_devops/pages/amap/widget/amap_widget.dart';
import 'package:yt_devops/pages/amap/widget/google_map_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:geolocator/geolocator.dart';

class AmapPageController extends GetxController {
  TextEditingController textController = TextEditingController();

  // AMapPoi? _poiInfo;

  Map<String, Marker> markers = <String, Marker>{};

  LatLng? initLocation;

  String initAddress = '';

  int mapType = 0;

  GlobalKey<AmapWidgetState> amapKey = GlobalKey();

  GlobalKey<GoogleMapWidgetState> googlemapKey = GlobalKey();

  @override
  void onInit() {
    if (Get.arguments != null) {
      if (Get.arguments['latitude'] != null &&
          Get.arguments['longitude'] != null) {
        initLocation =
            LatLng(Get.arguments['latitude'], Get.arguments['longitude']);
      } else {
        _requestLocationPermission().then(
          (value) {
            if (value) {
              _getCurrentLocation();
            }
          },
        );
      }
      if (Get.arguments['address'] != null &&
          Get.arguments['address'] != null) {
        initAddress = Get.arguments['address'];
      }
      if (Get.arguments['mapType'] != null) {
        mapType = Get.arguments['mapType'];
      }
    } else {}
    super.onInit();
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> _requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  void submit(poi) {
    Get.back();
    Get.back(result: poi);
  }

  _getCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    Log.d('position==' + position.latitude.toString());
    if (position != null) {
      initLocation = LatLng(position.latitude, position.longitude);
      update();
    }
  }

  _showMyLocation() async {
    XbrGaodeLocation.instance().startTimeLocation(
        callback: (LocationInfo? location) {
      if (initLocation != null) {
        return;
      }
      if (location == null ||
          location.latitude == null ||
          location.longitude == null) return;

      initLocation = LatLng(location.latitude!, location.longitude!);

      ///利用地图控制器移动到定位点 2s动画
      // LatLng latLng = LatLng(location.latitude!, location.longitude!);
      // initLocation = latLng;
      // amapController.moveCamera(CameraUpdate.newLatLngZoom(latLng, 16),
      //     duration: 250);

      ///刷新UI
      update();
    });
  }

  void onPoiTouched(BuildContext context, AmapPoi poi) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        height: 305.h,
        padding: EdgeInsets.fromLTRB(20.w, 20, 20.w, 0),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.w), color: Colour.white),
        child: Column(children: [
          SizedBox(
            child: Text(
              poi.formattedAddress ?? '',
              style: TextStyles.f16.boldStyle,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          const SizedBox(
            height: 24,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                ResKey.longitude.tr,
                style: TextStyles.f14.copyWith(height: 3),
              ),
              Text(
                poi.latitude.toString(),
                style: TextStyles.lf14.copyWith(height: 3),
              )
            ],
          ),
          const Divider(
            color: Colour.dividerColor,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                ResKey.latitude.tr,
                style: TextStyles.f14.copyWith(height: 3),
              ),
              Text(
                poi.longitude.toString(),
                style: TextStyles.lf14.copyWith(height: 3),
              )
            ],
          ),
          const SizedBox(
            height: 40,
          ),
          YtButton(
            text: ResKey.confirm.tr,
            onPress: () => submit(poi),
          ),
          Gaps.hGap16
        ]),
      ),
    );
  }

  searchAroundAddress(BuildContext context, String text) {
    if (mapType == 0) {
      amapKey.currentState?.searchAroundAddress(context, text);
    } else {
      googlemapKey.currentState?.searchAroundAddress(text);
    }
  }

  @override
  void onClose() {
    XbrGaodeLocation.instance().destroyTimeLocation();
    super.onClose();
  }
}
